package com.syf.config.redis;

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * SpringCacheConfig配置文件：【当spring-cache缓存redis时返回对象/集合结果时配置】
 *  作用:
 *      1.把redis的value序列化器修改为 GenericJackson2JsonRedisSerializer，就支持返回值为对象或集合了
 *		2.当使用spring Cache返回值是对象/集合时，没有使用此配置文件，
 *         执行会报异常：java.io.StreamCorruptedException: invalid stream header: 225B7B5C
 */
@Configuration
public class SpringCacheConfig {
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //缓存配置对象
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();

        redisCacheConfiguration = redisCacheConfiguration
                .entryTtl(Duration.ofMinutes(30L))   //设置缓存的默认超时时间：30分钟
                .disableCachingNullValues()          //如果是空值，redis不缓存
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))         //设置key序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));  //设置value序列化器【jdk->Jackson】

        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }
}
